package com.elm.service.impl;

import com.elm.mapper.DeliveryAddressMapper;
import com.elm.po.DeliveryAddress;
import com.elm.service.DeliveryAddressService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DeliveryAddressServiceImpl implements DeliveryAddressService {
    @Autowired
    private DeliveryAddressMapper addressMapper;
    @Autowired
    private HttpServletRequest request;

    private String getCurrentUserId() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserIdFromToken(token);
    }

    @Override
    public List<DeliveryAddress> getDeliveryAddressByUserId(String userId) {
        // 验证地址所属权
        if (!userId.equals(getCurrentUserId())) {
            throw new RuntimeException("无权限查看他人地址");
        }
        return addressMapper.getDeliveryAddressByUserId(userId);
    }

    @Override
    public int saveDeliveryAddress(DeliveryAddress deliveryAddress) {
        deliveryAddress.setUserId(getCurrentUserId());
        return addressMapper.saveDeliveryAddress(deliveryAddress);
    }

    @Override
    public DeliveryAddress getDeliveryAddressById(Integer daId) {
        DeliveryAddress address = addressMapper.getDeliveryAddressById(daId);
        if (!address.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("无权限查看他人地址");
        }
        return address;
    }

    @Override
    public int updateDeliveryAddress(DeliveryAddress deliveryAddress) {
        DeliveryAddress oldAddress = addressMapper.getDeliveryAddressById(deliveryAddress.getDaId());
        if (!oldAddress.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("无权限修改他人地址");
        }
        return addressMapper.updateDeliveryAddress(deliveryAddress);
    }

    @Override
    public int removeDeliveryAddress(Integer daId) {
        DeliveryAddress address = addressMapper.getDeliveryAddressById(daId);
        if (!address.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("无权限删除他人地址");
        }
        return addressMapper.removeDeliveryAddress(daId);
    }

    @Override
    public int setDefaultAddress(Integer daId) {
        DeliveryAddress address = addressMapper.getDeliveryAddressById(daId);
        if (!address.getUserId().equals(getCurrentUserId())) {
            throw new RuntimeException("无权限设置他人地址为默认");
        }
        return addressMapper.setDefaultAddress(daId);
    }
}